package org.blindmandesign;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.    
 */

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Nathan Bubna
 * @since javaQuery 1.0
 * @version $Id$
 */
public class Tag extends Node<Tag> {

    private Object name;
    private Object id;
    private List<Object> classes;
    private Map<Object,Object> attributes;
    private List<Node> children;

    public NodeType getType() {
        return NodeType.TAG;
    }

    public Tag name(Object name) {
        this.name = name;
        return this;
    }

    public Tag id(Object id) {
        this.id = id;
        return this;
    }

    public Tag addClass(Object c) {
        if (c == null) {
            return null;
        }

        if (classes == null) {
            classes = new ArrayList<Object>();
        }
        classes.add(c);
        return this;
    }

    public Tag attr(Object k, Object v) {
        if (k == null) {
            return null;
        }
        if (attributes == null) {
            attributes = new LinkedHashMap<Object,Object>();
        }
        attributes.put(k, v);
        return this;
    }

    public String text() {
        if (isEmpty()) {
            return "";
        }
        StringBuilder out = new StringBuilder();
        text(out);
        return out.toString();
    }

    public Tag text(StringBuilder out) {
        for (Node n : children) {
            if (n.getType() == NodeType.TEXT) {
                ((Text)n).render(out);
            }
        }
        return this;
    }

    public Tag text(Object o) {
        Text t = o instanceof Text ? (Text)o : new Text(o);
        if (children == null) {
            children = new ArrayList<Node>();
        }
        else {
            children.clear();
        }
        children.add(t);
        return this;
    }

    public Tag append(Object o) {
        Node n = o instanceof Node ? (Node)o : new Text(o);
        if (children == null) {
            children = new ArrayList<Node>();
        }
        children.add(n);
        n.parent(this);
        return this;
    }

    public Tag prepend(Object o) {
        Node n = o instanceof Node ? (Node)o : new Text(o);
        if (children == null) {
            children = new ArrayList<Node>();
            children.add(n);
        }
        else {
            children.add(0, n);
        }
        n.parent(this);
        return this;
    }

    @Override
    public Tag root() {
        if (isOrphan()) {
            return this;
        }
        return parent().root();
    }

    public List<Tag> children() {
        return find(null);
    }

    public boolean isEmpty() {
        return (children == null || children().isEmpty());
    }

    public boolean matches(Node n) {
        // no arrow, no miss
        if (n == null) {
            return true;
        }
        if (n.getType() != NodeType.TAG) {
            return false;
        }
        Tag tag = (Tag)n;
        if (missed(name, tag.name) ||
            missed(id, tag.id) ||
            missed(classes, tag.classes) ||
            missed(attributes, tag.attributes)) {
            return false;
        }
        if (!tag.isEmpty()) {
            // no targets, always miss
            if (isEmpty()) {
                return false;
            }
            for (Node kid : tag.children()) {
                if (kid.getType() != NodeType.TAG) {
                    if (find((Tag)kid, false) == null) {
                        return false;
                    }
                }
                else if (!children.contains(kid)) {
                    return false;
                }
            }
        }
        return true;
    }

    public List<Tag> find(Tag matchMe) {
        return (List<Tag>)find(matchMe, true);
    }

    protected Object find(Tag matchMe, boolean all) {
        if (children == null) {
            return all ? Collections.emptyList() : null;
        }
        List<Tag> kids = null;
        for (Node kid : children) {
            if (kid.getType() == NodeType.TAG && 
                (matchMe == null || kid.matches(matchMe))) {
                if (all) {
                    if (kids == null) {
                        kids = new ArrayList<Tag>();
                    }
                    kids.add((Tag)kid);
                }
                else {
                    return kid;
                }
            }
        }
        return kids;
    }

    protected boolean missed(Object target, Object arrow) {
        // no arrow, no miss
        if (arrow == null) {
            return false;
        }
        // otherwise, the arrow must equal the target
        return !arrow.equals(target);
    }

    protected boolean missed(Collection<Object> targets, Collection<Object> arrows) {
        // no arrows, no miss
        if (arrows == null || arrows.isEmpty()) {
            return false;
        }
        // no targets, always miss
        if (targets == null || targets.isEmpty()) {
            return true;
        }
        for (Object o : arrows) {
            if (!targets.contains(o)) {
                return true;
            }
        }
        return false;
    }

    protected boolean missed(Map<Object,Object> targets, Map<Object,Object> arrows) {
        if (arrows == null || arrows.isEmpty()) {
            return false;
        }
        if (targets == null || targets.isEmpty()) {
            return true;
        }
        for (Map.Entry<Object,Object> entry : arrows.entrySet()) {
            Object key = entry.getKey();
            if (!targets.containsKey(key) ||
                missed(targets.get(key), entry.getValue())) {
                return true;
            }
        }
        return false;
    }


    /************* rendering methods **************/

    public void render(StringBuilder s, Config config) {
        render(config.getNewLine(), s, config);
    }

    public void render(String indent, StringBuilder s, Config config) {
        if (render_start(indent, s)) {
            render_body(indent, s, config);
            render_end(indent, s);
        }
    }

    protected boolean render_start(String indent, StringBuilder s) {
        if (indent != null && s.length() > 0) {
            s.append(indent);
        }
        s.append('<');
        render_name(s);
        render_id(s);
        render_classes(s);
        render_attributes(s);
        if (isEmpty()) {
            s.append("/>");
            return false;
        }
        else {
            s.append('>');
            return true;
        }
    }

    protected void render_name(StringBuilder s) {
        s.append(name == null ? "div" : name);
    }

    protected void render_id(StringBuilder s) {
        if (id != null) {
            s.append(" id=\"").append(id).append('"');
        }
    }

    protected void render_classes(StringBuilder s) {
        if (classes != null) {
            s.append(" class=\"");
            for (int i=0; i < classes.size(); i++) {
                s.append(classes.get(i));
                if (i + 1 != classes.size()) {
                    s.append(' ');
                }
            }
            s.append('"');
        }
    }

    protected void render_attributes(StringBuilder s) {
        if (attributes != null) {
            for (Map.Entry<Object,Object> entry : attributes.entrySet()) {
                s.append(' ').append(entry.getKey()).append("=\"");
                if (entry.getValue() != null) {
                    s.append(entry.getValue());
                }
                s.append('"');
            }
        }
    }

    protected void render_body(String indent, StringBuilder s, Config config) {
        String kidIndent = indent + config.getTab();
        for (Node n : children) {
            n.render(kidIndent, s, config);
        }
    }

    protected void render_end(String indent, StringBuilder s) {
        if (indent != null) {
            s.append(indent);
        }
        s.append("</").append(name).append('>');
    }

}
